//
//  PlayerManager.m
//  MusicDemos
//
//  Created by xalo on 16/6/16.
//  Copyright © 2016年 蓝鸥科技有限公司西安分公司. All rights reserved.
//

#import "PlayerManager.h"
#import <AVFoundation/AVFoundation.h>

@interface PlayerManager ()
@property (nonatomic,strong)AVPlayer *player;
@property (nonatomic,strong)NSTimer *timer;//定时器
@end


@implementation PlayerManager

-(NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;
}
//定时器方法
-(void)timerAction{

//    NSLog(@"%ld",(long)[self fetchCurrentTime]);
    if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
        [self.delegate playManagerDelegateFetchTotalTime:[self changeSecondTime:[self fetchTotalTime]] currentTime:[self changeSecondTime:[self fetchCurrentTime ]] progress:[self fetchProgressValue ]];
    }
}

//开启定时器
-(void)startTimer{
    [self.timer fire];

}

//关闭定时器
-(void)closeTimer{
    [self.timer invalidate];
    self.timer = nil;//定时器置空
}


+(instancetype)defaultManager{
    static PlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PlayerManager alloc]init];
    });
    return manager;
}
-(AVPlayer *)player{
    if (!_player) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}
//暂停
-(void)pauseMusic{
    
    [self.player pause];
    [self closeTimer];
}
//播放
-(void)playMusic{
    
    [self.player play];
    [self startTimer];
    
}
//是否正在播放
-(BOOL)isPlaying{
    if (self.player.rate) {
        return YES;
    }else{
        return NO;
    }
    
    
}

//准备去播放
-(void)prepareToPlayMusicWithURL:(NSString *)url{
   //如果网址为空，则不执行任何操作
    if (!url) {
        return;
    }
    //判断当前有没有正在播放的item
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    //创建一个Item
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    //观察item的加载状态
   [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    //替换item
    [self.player replaceCurrentItemWithPlayerItem:item];
    //播放完成后自动跳到下一首
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playMusicEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}
//自动播放下一首事件
-(void)playMusicEnd{
    if ([self.delegate respondsToSelector:@selector(playToNextMusic)]) {
        [self.delegate playToNextMusic];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
}
//添加观察者事件
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    // 得到属性改变后的状态
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"Unknown");
            break;
            case AVPlayerItemStatusReadyToPlay:
            //调用播放方法
            [self playMusic];
            NSLog(@"readyToPlay");
            break;
            case AVPlayerItemStatusFailed:
            NSLog(@"failed");
            break;
        default:
            break;
    }
    
    
    
}
//获取总时长
-(NSInteger)fetchTotalTime{
    //获取档期播放总时间
    
    CMTime time = self.player.currentItem.duration;
    //播放秒数
    if (time.timescale == 0 ) {
        return 0;
    }
    return time.value/time.timescale;
}

//获取当前播放时间
-(NSInteger)fetchCurrentTime{
    CMTime  time = self.player.currentItem.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    
    return time.value/time.timescale;
}

//获取当前播放进度
-(CGFloat)fetchProgressValue{
    return [self fetchCurrentTime]/(CGFloat)[self fetchTotalTime];
}

//将描述秒数转换成类似00:00的时间格式
-(NSString *)changeSecondTime:(NSInteger)time{
    NSInteger min = time/60;
    NSInteger sec = time%60;
    NSString *string = [NSString stringWithFormat:@"%.2ld:%.2ld",min,sec];
    return string;
}

//快进快退
-(void)playMusicWithSliderValue:(CGFloat)progress{
    //滑动之前先暂停音乐
    [self pauseMusic];
    [self.player seekToTime:CMTimeMake([self fetchTotalTime]*progress, 1) completionHandler:^(BOOL finished) {
        if (finished) {
            [self playMusic];
        }
    }];
}

























@end